{qiniu} = require '../config'
db = require './connect'
async = require 'async'
request = require 'request'

headimg = (done)->
	headimg = new qiniu.Bucket('headimg')

	sql = "select * from accounts where isheadimg = 0"
	db.runSql sql, (err,results)->
		console.log err if err
		async.forEachSeries results,(account, callback)->
			async.series [ 
				(cb)->
					ps = headimg.createPutStream(account.username + '.jpg')
					jar = request.jar()
					ps.on 'error',(err)->
						console.log err if err
					ps.on 'end',(result)-> 
						cb null
					cookies = "speedup=sdch; ptui_loginuin=2836874539; pt2gguin=o2836874539; RK=oWQKKtEean; ptcz=999ddb8b8111a23d6d2b7d130e4781f0b1e68db673ee2fb53a81faaae4d79788; pgv_pvid=3015879784; o_cookie=2836874539; webwxuvid=926663722; wxuin=1028001812; wxsid=KpkR3PweTr2KUHV; wxstaytime=1378993210; mm_lang=zh_CN\; wxpluginkey=1378978802"
					for a in cookies.split ';'
						cookie = request.cookie a
						jar.add(cookie)
					url = 'http://wx.qq.com'+account.headimgurl
					request({url,jar}).pipe ps
				(cb)->
					sql = "update accounts set isheadimg = 1 where id = ?"
					db.runSql sql , [account.id], cb
			],callback
		,done

headimg ()->
	console.log arguments